package com.ipzoe.web.token;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ipzoe.common.core.domain.AjaxResult;
import com.ipzoe.common.jwt.JwtTokenUtil;
import com.ipzoe.common.utils.ServletUtils;
import com.ipzoe.common.utils.spring.SpringContextHolder;
import com.ipzoe.mem.domain.Member;
import com.ipzoe.mem.service.IMemberService;
import com.ipzoe.web.core.consts.Constant;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private IMemberService iMemberService;

    public static final String[] NONE_AUTHED_STATIC_RESOURCES = {
            "/css/**",
            "/js/**",
            "/image/**",
            "/favicon.ico"
    };

    public static final String[] NEED_AUTH_RESOURCES = {
            "/user/detail",
            "/user/exchange",
            "/user/edit",
            "/activity/signUp",
            "/wxPay/scanCode2"
    };

    public JwtAuthorizationTokenFilter() {
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 1.静态资源直接过滤，不走此过滤器
        for (String reg : NONE_AUTHED_STATIC_RESOURCES) {
            if (new AntPathMatcher().match(reg, request.getServletPath())) {
                chain.doFilter(request, response);
                return;
            }
        }

        int port = request.getServerPort();
        String serverName = request.getServerName();
        String contextPath = request.getContextPath();
        String activeProfile = SpringContextHolder.getApplicationContext().getEnvironment().getActiveProfiles()[0];
        StringBuilder loginRedirectUrl = new StringBuilder();
        if ("prod".equals(activeProfile)) {
            loginRedirectUrl.append("https");
        }else{
            loginRedirectUrl.append("http");
        }
        loginRedirectUrl.append("://").append(serverName);
        if(port != 80 && port != 443) {
            loginRedirectUrl.append(":").append(port);
        }
        if(contextPath != null) {
            loginRedirectUrl.append(contextPath);
        }
        loginRedirectUrl.append("/login");

        // 2.从cookie和header获取token
        String authToken = TokenUtil.getToken(request);

        // 3.通过token获取用户id
        Long userId = null;
        if (StrUtil.isNotEmpty(authToken)) {
            try {
                userId = Long.valueOf(jwtTokenUtil.getClaimFromToken(authToken).getSubject());
            } catch (IllegalArgumentException | JwtException e) {

            }
        }

        //4.如果未获取到userid，如果是必须要登录才能访问的那么跳转到登录
        if(userId == null){

            for (String reg : NEED_AUTH_RESOURCES) {
                if (new AntPathMatcher().match(reg, request.getServletPath())) {
                    if (ServletUtils.isAjaxRequest(request)) {
                        response.setCharacterEncoding("UTF-8");
                        response.setContentType("application/json; charset=utf-8");
                        PrintWriter out = response.getWriter();
                        out.append(JSON.toJSONString(AjaxResult.error(401, "您还未登录，请先登录")));
                        return;
                    }else{
                        //跳转到登录页面
                        response.sendRedirect(loginRedirectUrl.toString());
                        return;
                    }
                }
            }


        }else{

            //5.查询用户是否存在,或者冻结
            Member member = iMemberService.getById(userId);
            if(member == null || member.getStatus()==2){
                if (ServletUtils.isAjaxRequest(request)) {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json; charset=utf-8");
                    PrintWriter out = response.getWriter();
                    out.append(JSON.toJSONString(AjaxResult.error(401, "该账户不存在或者已经冻结")));
                    return;
                }else{
                    Cookie cookie = new Cookie(Constant.TOKEN_HEADER_NAME, null);
                    cookie.setPath("/");
                    cookie.setHttpOnly(true);
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                    response.sendRedirect(loginRedirectUrl.toString());
                    return;
                }

            }else{
                //6.将member存在request中
                request.setAttribute("member", member);
            }
        }
        chain.doFilter(request, response);
    }
}
